﻿using System;
using System.Text;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class Emails : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
   

  }
  protected void bnFind_Click(object sender, EventArgs e)
  {
    using (SqlConnection conn = Conn.GetOpened())
    {
      string sql = "select first_name,last_name,email from people where " + ddlFilter.SelectedValue + " order by email";
      using (SqlCommand comm = new SqlCommand(sql, conn))
      {
        using (SqlDataReader rdr = comm.ExecuteReader())
        {
          StringBuilder sb = new StringBuilder();
          sb.AppendLine("First Name,Last Name,Email,Formatted Email");
          while (rdr.Read())
          {
            string firstName = Util.ToText(rdr.GetSqlString(0));
            string lastName = Util.ToText(rdr.GetSqlString(1));
            string email = Util.ToText(rdr.GetSqlString(2));
            if (email.Contains('@')) // This person must have an email address
            {
              sb.Append(Util.CsvEscape(firstName)).Append(',');
              sb.Append(Util.CsvEscape(lastName)).Append(',');
              sb.Append(Util.CsvEscape(email)).Append(',');
              sb.Append(Util.CsvEscape(string.Format("{0} {1} <{2}>;", firstName, lastName, email))).AppendLine();
            }
          }
          sb.AppendLine("-end-");

          // Return it as a download to the user
          Response.Clear();
          Response.ContentType = "text/csv";
          Response.AppendHeader("Content-Disposition", "attachment; filename=EmailsExport.csv");
          Response.Write(sb.ToString());
          Response.End();
        }
      }
    }
  }
}
